package com.xuecheng.content.service.impl;

import com.alibaba.fastjson.JSON;
import com.xuecheng.basic.api.BasicClient;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.vo.CategoryVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.model.vo.TeachplanVo;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.domain.CourseBase;
import com.xuecheng.content.domain.CoursePub;
import com.xuecheng.content.domain.Teachplan;
import com.xuecheng.content.mappers.CoursePubMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.CoursePubService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 课程发布 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-16
 */
@Service
public class CoursePubServiceImpl extends ServiceImpl<CoursePubMapper, CoursePub> implements CoursePubService {

    @Autowired
    private TeachplanService teachplanService;
    @Autowired
    private CourseBaseService courseBaseService;
    @Autowired
    private BasicClient basicClxient;
    /**
     * 获取预览的课程发布数据
     *  1、课程信息
     *  2、课程老师
     *  3、课程大纲信息
     * 将3部分数据，转化成页面所需要的map集合
     *  coursePub：课程发布对象数据
     *  teachplanNode：课程计划数据
     */
    //课程发布预览
    @Override
    public Map preview(Long courseBaseId) {
        //判断参数
        if (courseBaseId==null){
            throw new BusinessException(ErrorCode.ERROR);
        }
        //查询课程大纲信息
        ResponseResult<TeachplanVo> treeNodes = teachplanService.treeNodes(courseBaseId);
        TeachplanVo vo = treeNodes.getData();
        //查询课程的基本信息
        CourseBase courseBase = courseBaseService.getById(courseBaseId);
        //老师信息
        //在freemarker模板端，通过操作课程发布对象，展示数据（courseBase，讲师信息）
        CoursePub coursePub = BeanHelper.copyProperties(courseBase, CoursePub.class);
        coursePub.setCourseId(courseBaseId);
        //大小分类
        coursePub.setMtName(getCategoryName(courseBase.getMt()));
        coursePub.setStName(getCategoryName(courseBase.getSt()));
        //课程大纲
        coursePub.setTeachplan(JSON.toJSONString(vo));
        //构造返回值
        Map map = new HashMap();
        map.put("teachplanNode",vo);
        map.put("coursePub",coursePub);
        return map;

    }

    //根据id，调用feign接口查询分类名称
    public String getCategoryName(String id) {
        ResponseResult<CategoryVo> result = basicClxient.findById(id);
        CategoryVo categoryVo = result.getData();
        return categoryVo.getName();
    }
}
